package br.panthro.utils.loading
{
	import br.panthro.utils.loading.IAssetLoader;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.utils.getQualifiedClassName;
	
	public class AssetLoader extends Sprite implements IAssetLoader
	{
		private var _loader:Loader;
		private var _asset:DisplayObject;
		private var _cueID:Number;
		private var _progress:Number;
		
		public function load(url:String):void
		{
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, loadComplete );
			_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, loadError );
			_loader.contentLoaderInfo.addEventListener( IOErrorEvent.NETWORK_ERROR, loadError );
			_loader.load(new URLRequest(url));
			
		}
		public function onProgress(event:ProgressEvent):void
		{
			_progress = (event.currentTarget.bytesLoaded / event.currentTarget.bytesTotal)*100;
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS));
		}
		public function loadComplete(event:Event):void
		{
			_asset = _loader.content;
			if(getQualifiedClassName(event.target.loader.content) == "flash.display::Bitmap")
			{
				event.target.loader.content.smoothing = true;
			}
			dispatchEvent(new AssetLoadEvent(AssetLoadEvent.LOAD_COMPLETE));
		}
		
		public function loadError(event:IOErrorEvent):void
		{
			dispatchEvent(new AssetLoadEvent(AssetLoadEvent.LOAD_ERROR));
		}
		public function set cueId(id:Number):void
		{
			_cueID = id;
		}
		public function get cueId():Number
		{
			return _cueID;
		}
		public function get content():DisplayObject
		{
			return _asset;
		}
		public function get progress():Number
		{
			return _progress;
		}
	}
}